package com.qingmu.club.minaapi.controller;


import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by linjie on 16/12/4.
 */

@RestController
@Api(value = "文件上传", description = "图片和文件上传管理都在这里")
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@RequestMapping(value = "/plus/file")
public class FileController {

    @Value("${web.upload-path}")
    private String uploadPath;
    @Value("${web.imageService}")
    private String wanPath;


    @RequestMapping(value = "/upload", method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "单文件上传")
    public ResponseEntity handleFileUpload(HttpServletRequest req,
                                           @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return ResponseObject.error(ResponseObject.ResponseCode_PARAM_ERROR, "文件为空");
        }

        try {
            //上传至服务器
            String filePath = this.remoteFilePath(file);

            return ResponseObject.success(wanPath+filePath);

        } catch (Exception e) {

            return ResponseObject.error(ResponseObject.ResponseCode_PARAM_ERROR, "文件错误" + e.getMessage());
        }
    }


    @RequestMapping(value = "/multiupload", method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "多文件件上传,最多5个（上传至服务器）")
    public ResponseEntity handleMultiFileUpload(HttpServletRequest req,
                                                @RequestParam(required = false) MultipartFile file1,
                                                @RequestParam(required = false) MultipartFile file2,
                                                @RequestParam(required = false) MultipartFile file3,
                                                @RequestParam(required = false) MultipartFile file4,
                                                @RequestParam(required = false) MultipartFile file5
    ) {


        List<String> imgPathList = new ArrayList<String>();

        try {
            if (file1 != null && !file1.isEmpty()) {

                //上传至服务器
                String path = this.remoteFilePath(file1);
                if (path != null) {
                    imgPathList.add(req.getRequestURI() + path);
                }
            }

            if (file2 != null && !file2.isEmpty()) {

                //上传至服务器
                String path = this.remoteFilePath(file2);


                if (path != null) {
                    imgPathList.add(req.getRequestURI() + path);
                }

            }
            if (file3 != null && !file3.isEmpty()) {

                //上传至服务器
                String path = this.remoteFilePath(file3);

                if (path != null) {
                    imgPathList.add(req.getRequestURI() + path);
                }

            }
            if (file4 != null && !file4.isEmpty()) {

                //上传至服务器
                String path = this.remoteFilePath(file4);


                if (path != null) {
                    imgPathList.add(req.getRequestURI() + path);
                }

            }
            if (file5 != null && !file5.isEmpty()) {

                //上传至服务器
                String path = this.remoteFilePath(file5);


                if (path != null) {
                    imgPathList.add(req.getRequestURI() + path);
                }

            }
        } catch (Exception e) {
            return ResponseObject.error(ResponseObject.ResponseCode_PARAM_ERROR, "文件错误" + e.getMessage());
        }

        if (imgPathList.size() == 0) {
            return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED, "没有找到图片文件");
        }

//        HashMap<String, Object> mm = new HashMap<String, Object>();
//        mm.put("urllist", imgPathList);
        return ResponseObject.success("urlList",imgPathList);
    }



    private String fileUrlPath(MultipartFile file) {


        String filename = file.getOriginalFilename();

        int pos = filename.lastIndexOf(".");
        String extName = "";

        if (pos != -1) {

            extName = filename.substring(pos + 1);

        }


        String newFileName = new Date().getTime() + "." + extName;

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

        String dateString = df.format(new Date());

        String newFilePath = "/upload/" + dateString + "/" + newFileName;

        return newFilePath;

    }


    //生成远程的文件名和路径
    private String remoteFilePath(MultipartFile file) {
        String filename = file.getOriginalFilename();
        int pos = filename.lastIndexOf(".");
        String extName = "";
        if (pos != -1) {
            extName = filename.substring(pos + 1);
        }

        String newFileName = new Date().getTime() + "." + extName;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dateString = df.format(new Date());
        String newFilePath = this.uploadPath + "/upload/" + dateString + "/";
        File checkFile = new File(newFilePath);
        if (!checkFile.exists() && !checkFile.isDirectory()) {
            checkFile.mkdirs();
        }
        String filePath = newFilePath + newFileName;
        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            String iconFilePath = newFilePath + "icon_" + newFileName;
            Thumbnails.of(file.getInputStream()).scale(0.25).outputQuality(0.25).toFile(iconFilePath);
            String smallFilePath = newFilePath + "small_" + newFileName;
            Thumbnails.of(file.getInputStream()).scale(0.5).outputQuality(0.7).toFile(smallFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return "/" + dateString + "/" + "small_"+newFileName;
    }




    private String saveToFile(String prefixPath, MultipartFile file,String type) {


        try {


            String newFileNameWithPath = this.remoteFilePath(file);


            byte[] bytes = file.getBytes();


            BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(newFileNameWithPath)));
            stream.write(bytes);
            stream.close();

            return prefixPath + "/" + this.fileUrlPath(file);


        } catch (Exception e) {

            return null;
        }


    }


}
